var AT_enable = false;
var TP_active = false;
var AT_Ctrl_Dev = false; // Control Device Enable
var callbackList = [];

var stationModeTag = sessionStorage.getItem("apt_PLC.OpcTopic") + sessionStorage.getItem("apt_PLC.Tags.OperationMode");

var ur = sessionStorage.getItem("apt_Config.Atomizer.UserRight");
var urNr = sessionStorage.getItem("apt_Config.Atomizer.UserRightNr");
var gr = sessionStorage.getItem("apt_Config.Atomizer.GroupRight");
var grNr = sessionStorage.getItem("apt_Config.Atomizer.GroupRightNr");

var rightsAvailable = false;
var stationMode = 0;


emosWS.advise(stationModeTag, function(msg){
    stationMode = msg.value;
    setAtEnable();
});

// Add event listener to check for user rights
emosWS.addEventListener("UserRight", function (msg) {
    // Check if users have right to release devices: 
    if (CheckUserRight(ur, urNr) || CheckUserRight(gr, grNr)) {
        rightsAvailable = true;
        setAtEnable();
    }
    else {
        rightsAvailable = false;
        setAtEnable();
    }
});

var nrChannels = configData["PCU1_ArraySize"]["Channel"];
var channelPrograms = {};

/*for(var i = 1; i <= nrChannels; i++){
    var tags = processTags["Channel[" + i + "].hmiIn.timeprogramActive"];
    emosWS.advise(tags, function(msg){
        if(parseInt(msg.value) !== 0) channelPrograms[msg.tag] = true;
        else channelPrograms[msg.tag] = false;
        var anyTrue = false;
        for(var key in channelPrograms){
            if(channelPrograms.hasOwnProperty(key)){
                if(channelPrograms[key] == true) {
                    anyTrue = true;
                    break;
                } 
            }
        }
        if(anyTrue){
            setTpVal(true);
        }
        else{
            setTpVal(false);
        }
    });
}


function setTpVal(val) {
    if (val !== TP_active) {
        TP_active = val;

        // Reinit the webpage
        // animationInitialize();
    }
}*/

function setAtEnable(){
    var localEnable = false;
    if(stationMode != 4 && rightsAvailable) localEnable = true;
    else localEnable = false;
    if (AT_enable !== localEnable) {
        AT_enable = localEnable;
        console.log("AT_enable " + AT_enable);
        pushAtEnabledToSubscribers();
        // animationInitialize();
    }
}


function subscribeAtEnabled(callback){
    callbackList.push(callback);
}

function pushAtEnabledToSubscribers(){
    callbackList.forEach(function(callback){
        callback.call(null, AT_enable);
    });
}